<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <el-form ref="pwdFormRef" :rules="rules" :model="dialogData.itemInfo" label-width="100px" label-suffix=" :">
      <el-form-item label="新密码" prop="password">
        <el-input v-model="dialogData.itemInfo.password" placeholder="请填写新密码" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="btnLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import md5 from "md5";
import { changeUserPasswordApi } from "@/api/modules/sys/user";

//页面的数据
interface PasswordDialogOption {
  //只有一个密码
  itemInfo: { password: string };
}
const dialogVisible = ref(false);
//提交按钮，避免多次提交
const btnLoading = ref(false);

const rules = reactive({
  password: [{ required: true, message: "请填写密码", trigger: "blur" }]
});

const dialogData = reactive<PasswordDialogOption>({
  itemInfo: { password: "" }
});

const pwdFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  pwdFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      await changeUserPasswordApi({
        npassword: md5(dialogData.itemInfo.password)
      });
      ElMessage.success({ message: `密码修改成功！` });
      //刷新列表数据
      dialogVisible.value = false;
    } catch (error) {
      //   console.log(error);
    } finally {
      btnLoading.value = false;
    }
  });
};

// openDialog
const openDialog = () => {
  dialogVisible.value = true;
};

defineExpose({ openDialog });
</script>
